<template>
	<view class="video-capture">
		<view class="btns">
			<button @click="chooseVideo">请选择视频</button>
		</view>
		<view class="url-input">
			<input type="text" v-model="videoUrl" placeholder="请输入视频地址" class="video-url-input" />
			<button @click="onPaser" class="url-button">粘贴</button>
			<button @click="loadVideoUrl" class="url-button">确定</button>
		</view>
		<view class="video-container" v-if="videoSrc">
			<video :src="videoSrc" id="myVideo" ref="videoRef" :loop="true" :controls="true" />
		</view>
		<view class="btns alls">
			<button @click="captureFrame">截取当前画面</button>
			<button @click="captureStartFrame">截取首帧画面</button>
			<button @click="captureEndFrame">截取尾帧画面</button>
		</view>

		<image v-if="imgSrc" :src="imgSrc" style="width: 100%;" mode="widthFix" @click="previewImage" />
		<view class="btns ups">
			<button @click="onUpload">上传当前图片</button>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { PlatformFactory } from './platform/PlatformFactory';
import {
	useLink
} from '../Test/hooks/useLink';
import {
	useResource
} from '../Test/hooks/useResource';
const SERVER_URL = 'https://jsz315.xyz/uni-record/resources'; // 常量定义
const {
	h5UploadBase64
} = useResource(SERVER_URL);
const {
	getVideoLink
} = useLink();
const platform = PlatformFactory.createPlatform();
const videoRef = ref<any>(null);
const videoSrc = ref('');
const duration = ref(0);
const currentTime = ref(0);
const videoUrl = ref(''); // 新增视频URL输入框的值

const imgSrc = ref('');

const onPaser = async () => {
	videoUrl.value = '';
	try {
		// 尝试读取剪贴板前再次请求权限
		await requestClipboardPermission();

		const text = await navigator.clipboard.readText();
		videoUrl.value = text;
		loadVideoUrl();
	} catch (err) {
		uni.showToast({
			title: '获取剪贴板失败，请检查权限',
			icon: 'none'
		});
		console.error('获取剪贴板失败:', err);
	}
}

const onUpload = () => {
	if (!imgSrc.value) {
		uni.showToast({ title: '请截取图片', icon: 'none' });
		return;
	}
	uni.showLoading({
		title: '上传中',
		mask: true
	});
	h5UploadBase64(imgSrc.value);
}
// 添加加载视频URL的方法
const loadVideoUrl = () => {
	if (!videoUrl.value) {
		uni.showToast({ title: '请输入视频地址', icon: 'none' });
		return;
	}

	getVideoLink(videoUrl.value).then((res) => {
		console.log("res", res);
		if (res.success) {
			videoSrc.value = res.message.medias[0].url;
		}

	})
	// videoSrc.value = videoUrl.value;
	// window.open(videoUrl.value, '_blank');
};

const chooseVideo = async () => {
	try {
		videoSrc.value = await platform.chooseVideo();
	} catch (error) {
		uni.showToast({ title: '选择视频失败', icon: 'none' });
	}
};

const previewImage = () => {
	// uni.previewImage({
	// 	current: imgSrc.value,
	// 	urls: [imgSrc.value],
	// });

	setTimeout(() => {
		console.log("window CYFUN", window["CYFUN"])
		window.top["CYFUN"]("saveImage", imgSrc.value)
	}, 30);

	// const link = document.createElement('a');
	// link.download = `${Date.now()}.png`;
	// link.href = imgSrc.value;
	// link.click();
}

const captureFrame = async () => {
	const video = platform.getVideoContext(videoRef.value);
	console.log("video", video);

	const canvas = document.createElement('canvas');
	canvas.width = video.videoWidth;
	canvas.height = video.videoHeight;
	const ctx = canvas.getContext('2d');
	if (ctx) {
		ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
		imgSrc.value = canvas.toDataURL('image/png');
	}
};

const captureStartFrame = async () => {
	const video = platform.getVideoContext(videoRef.value);
	// 设置视频时间为0，等待视频加载到首帧
	video.currentTime = 0;

	// 等待视频加载到指定时间
	await new Promise((resolve) => {
		video.addEventListener('seeked', resolve, { once: true });
	});
	const canvas = document.createElement('canvas');
	canvas.width = video.videoWidth;
	canvas.height = video.videoHeight;
	const ctx = canvas.getContext('2d');
	if (ctx) {
		ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
		imgSrc.value = canvas.toDataURL('image/png');
	}
};

// 请求剪贴板权限的方法
const requestClipboardPermission = async () => {
	try {
		// 检查权限状态
		const permissionStatus = await navigator.permissions.query({ name: 'clipboard-read' });
		console.log('剪贴板权限状态:', permissionStatus.state);

		// 如果权限状态不是 'granted'，可以显示提示
		if (permissionStatus.state !== 'granted') {
			uni.showToast({
				title: '请允许访问剪贴板以使用粘贴功能',
				icon: 'none',
				duration: 3000
			});
		}
	} catch (error) {
		console.error('请求剪贴板权限失败:', error);
	}
};
const captureEndFrame = async () => {
	const video = platform.getVideoContext(videoRef.value);
	// 设置视频时间为视频总时长，等待视频加载到最后一帧
	video.currentTime = video.duration;

	// 等待视频加载到指定时间
	await new Promise((resolve) => {
		video.addEventListener('seeked', resolve, { once: true });
	});
	const canvas = document.createElement('canvas');
	canvas.width = video.videoWidth;
	canvas.height = video.videoHeight;
	const ctx = canvas.getContext('2d');
	if (ctx) {
		ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
		imgSrc.value = canvas.toDataURL('image/png');
	}
};
</script>

<style lang="scss" scoped>
.video-capture {
	padding: 20rpx;
}

.video-container {
	width: 100%;
	aspect-ratio: 16/9;
	background: #000;
	margin-bottom: 20rpx;
}

.video-container video {
	width: 100%;
	height: 100%;
}

.controls {
	padding: 20rpx;
}

.btns {
	margin: 40rpx 0;
	display: flex;
	justify-content: center;
	gap: 20rpx;
}

.alls {
	:deep(uni-button) {
		background-color: #18a808;
	}
}

.ups {
	:deep(uni-button) {
		background-color: #de470c;
	}
}

:deep(uni-button) {
	border: none;
	border-radius: 4px;
	background-color: #007aff;
	color: #fff;
	cursor: pointer;
	flex: 1;
	font-size: 12px;
}

.url-input {
	display: flex;
	margin: 20rpx 0;
	gap: 20rpx;

	.video-url-input {
		flex: 1;
		width: 100%;
		height: 70rpx;
		border: 1px solid #ddd;
		border-radius: 4px;
		padding: 0 20rpx;
	}

	.url-button {
		width: 120rpx;
		white-space: nowrap;
		flex: none !important;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
	}
}
</style>